import { Message,Notification } from 'element-ui'
let _Remind = false;
const ops = {
  title:"网络异常",
  message:'实时数据获取失败,请检查网络',
  duration:0,
  position:'bottom-right',
  onClose:function(){
    _Remind = false;
  }
};
class WebSocketClass {
  constructor(name) {
    this.name = name;
    this.connect(name);
  }
  connect(name) {
    this.ws = new WebSocket(name);
    this.ws.onopen = e => {
      this.status = 'open';
      // Message.success('实时库连接成功');
      console.log(`${name}连接成功`, e);
      if(_Remind)_Remind = false
    };
    this.ws.onerror = e =>{
      // Message.warning('实时库连接出错，正在重新连接!')
      if(!_Remind)Notification.error(ops);
      _Remind = true;
      if(this.ws)close();
      setTimeout(()=>{
        this.connect(this.name);
      },3000)
    }
  }
  sendMessage = message => {
    setTimeout(() => {
      if (this.ws.readyState === 0) {
        this.sendMessage(message)
      } else {
        this.ws.send(JSON.stringify(message))
      }
    }, 1000)
  };
  getMessage(resMethods) {
    this.ws.onmessage = e => {
      resMethods(e.data)
    };
  }
  close() {
    // this.ws.send('close');
    this.ws.close();
    console.log('关闭成功'+new Date());
  }
}

export default WebSocketClass;
